import { createStore } from "vuex";
import { App } from "vue";
import { getUserInfo } from "../request/httpAPI";
interface menuObj {
  parentId: number;
  id: number;
  name: string;
  children?: menuObj[];
}
interface newMenuObj {
  [key: number | string]: menuObj;
}
interface State {
  menus: menuObj[];
}
const store = createStore<State>({
  state() {
    return {
      menus: [],
    };
  },
  getters: {
    getNewMenus(state) {
      // 预期数据 {'一级菜单列表id':全部内容,children:[{二级菜单全部内容}]}
      const newMenus: newMenuObj = {};
      const menus = state.menus;
      for (let i = 0; i < menus.length; i++) {
        // 一级菜单
        if (menus[i].parentId === 0) {
          newMenus[menus[i].id] = {
            ...menus[i],
            children: newMenus[menus[i].id]?.children || [], //当二菜单在一级菜单之前 处理
          };
        } else {
          // 二级菜单
          let parentId = menus[i].parentId; //对应一级菜单的id
          newMenus[parentId] = newMenus[parentId] || {}; //兼容 (相较于if更友好些)
          newMenus[parentId].children = newMenus[parentId].children || [];
          newMenus[parentId].children?.push(menus[i]);
        }
      }
      return newMenus;
    },
  },
  mutations: {
    // 更新用户信息
    updateMenus(state, menus) {
      state.menus = menus;
    },
  },
  actions: {
    updateMenus({ commit }) {
      return new Promise((resolve, reject) => {
        // 获取用户信息
        getUserInfo()
          .then((res) => {
            if (res.code === 200) {
              // (res);
              commit("updateMenus", res.data.menus); // 获取数据存储到vuex
              resolve(res.data);
            } else {
              reject(res);
            }
          })
          .catch((err) => {});
      });
    },
  },
  modules: {},
});
// 不暴露在外面 router也可以这样写
export const initStore = (app: App<Element>) => {
  app.use(store);
};
export default store;
/* import { InjectionKey } from "vue";
import { createStore, Store } from "vuex";

export interface State {}

export const key: InjectionKey<Store<State>> = Symbol();

export const store = createStore<State>({
  state() {
    return {};
  },
  mutations: {},
});
 */
